<template>
  <div class="search-container">
    <!-- 搜索框 -->
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索 子组件 -->
    <SearchResult v-if="isResultShow" :search-text="searchText" />
    <SearchHistory
      v-else-if="!searchText"
      :searchHistories="searchHistories"
      @search="onSearch"
      @clear-search-histroies="searchHistories = []"
    />
    <SearchSuggest v-else :search-text="searchText" @search="onSearch" />
  </div>
</template>

<script>
// 导入三个搜索 子组件
import SearchHistory from '@/views/search/components/search-histroy.vue'
import SearchResult from '@/views/search/components/search-result.vue'
import SearchSuggest from '@/views/search/components/search-suggest.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggest
  },
  data () {
    return {
      isResultShow: false, // 显示搜索结果
      searchText: null,
      searchHistories: getItem('TOUTIAO_SEARCH_HISTROIES') || [] // 搜索历史记录
    }
  },
  watch: {
    // 监视历史数据的变化
    searchHistories (value) {
      setItem('TOUTIAO_SEARCH_HISTROIES', value)
    }
  },
  created () {

  },
  methods: {
    // 按下搜索键 或者enter
    onSearch (value) {
      // 将点击的 数据项 填充到搜索框中
      this.searchText = value
      // 存储搜索历史记录 每增加一个都遍历一次 去掉相同的再追加到最前面
      const index = this.searchHistories.indexOf(value)
      if (index >= 1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(value)
      // 显示搜索结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    left: 0px;
    top: 0px;
    right: 0px;
    z-index: 1;
  }
}
</style>
